
class KankanwuSearch extends AbstractPlugin {

  static BASE_URL = 'https://www.kankanwu.com';

  async fetchSearchResults(query) {
    const searchUrl = `${KankanwuSearch.BASE_URL}/index.php?s=vod-search-wd-${encodeURIComponent(query)}-1-ajax`;
    const http_headers = {
      'User-Agent': KankanwuSearch.DEFAULT_USER_AGENT,
      'Origin': KankanwuSearch.BASE_URL,
      'x-requested-with': 'XMLHttpRequest'
    };
    const result  = await doHttpRequestSync(searchUrl, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const data = result.body;

    const searchResults = [];
    try {
      const result = JSON.parse(data);
      if(result && result.hasOwnProperty('data') && result.data.hasOwnProperty('ajaxtxt')) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(result.data.ajaxtxt, 'text/html');

        const results = doc.querySelectorAll('li');
        results.forEach(result => {
          const searchResult = new SearchResult();
          searchResult.site_icon = '/plugins/kankanwu/icon.png';
          searchResult.site_name = KankanwuSearch.BASE_URL.replace(/https?:\/\/(www\.)?/, '');

          const imageElement = result.querySelector('.play-img img');
          searchResult.image = imageElement ? imageElement.getAttribute("src").trim() : '';

          const titleElement = result.querySelector('.play-txt h5 a');
          searchResult.title = titleElement ? titleElement.textContent.trim() : '';

          const href = titleElement ? titleElement.getAttribute('href') : '';
          searchResult.link = href.startsWith('/') ? `${KankanwuSearch.BASE_URL}${href}` : href;

          const infos = [];
          result.querySelectorAll('p:not(.more-desc)').forEach(infoElement => {
            infos.push(infoElement.textContent.trim());
          });
          searchResult.description = infos.join('\n');

          searchResults.push(searchResult);
        });
      }
    } catch(e) {
      return searchResults;
    }
    return searchResults;
  }

}
Registry.registerClass("KankanwuSearch", new KankanwuSearch());